package unixsock

import (
	"encoding/json"
	v1 "k8s.io/client-go/listers/core/v1"
	"net"
	"operator/pkg/format"
	unix2 "operator/pkg/types/unix"
	"operator/pkg/util"
	"os"
)

type UnixSocket struct {
	addr      string
	podLister v1.PodLister
}

func (unix *UnixSocket) dealConn(conn net.Conn) {
	buf := make([]byte, 1024*30)
	for {
		n, err := conn.Read(buf)
		if err != nil {
			format.Errors("pkg/unixsocket/sock.go", 23, err.Error())
			break
		}

		var request unix2.UnixRequest
		err = json.Unmarshal(buf[:n], &request)
		if err != nil {
			format.Errors("pkg/unixsocket/sock.go", 32, err.Error())
			response := unix2.Error(err.Error())
			conn.Write(response.Bytes())
			continue
		}

		err = request.Validate()
		if err != nil {
			response := unix2.Error(err.Error())
			conn.Write(response.Bytes())
			continue
		}
		format.Println("pkg/unixsocket/sock.go", 45, util.JsonEncode(request))

		pod, err := unix.podLister.Pods(request.NameSpace).Get(request.Name)
		if err != nil {
			response := unix2.Error(err.Error())
			conn.Write(response.Bytes())
			continue
		}

		pod.Kind = "Pod"
		pod.APIVersion = "v1"
		data, err := json.Marshal(pod)
		if err != nil {
			response := unix2.Error(err.Error())
			conn.Write(response.Bytes())
			continue
		}

		response := unix2.Ok(string(data))
		conn.Write(response.Bytes())
	}
}

func (unix *UnixSocket) Run(stopCh <-chan struct{}) {
	lisnter, err := net.Listen("tcp", unix.addr)
	if err != nil {
		format.Errors("pkg/unixsocket/sock.go", 69, err.Error())
		os.Exit(1)
	}
	for {
		select {
		case <-stopCh:
			break
		default:
			conn, err := lisnter.Accept()
			if err != nil {
				format.Errors("pkg/unixsocket/sock.go", 79, err.Error())
				continue
			}

			go unix.dealConn(conn)
		}
	}
}

func NewDefaultUnix(lister v1.PodLister) *UnixSocket {
	u := &UnixSocket{
		addr:      "0.0.0.0:25500",
		podLister: lister,
	}

	return u
}
